<?php

namespace App\Http\Controllers\Api;

use App\Models\Shop\Address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;

class AddressController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index(Request $request)
   {
      $addresses = Address::all_addresses();
      return response()->json($addresses)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
   }

   /**
    * Store a newly created resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id

      Address::create([
         'user_id' => $user->id,
         'name' => $request->name,
         'provice' => $request->provice,
         'city' => $request->city,
         'area' => $request->area,
         'detail' => $request->detail,
         'tel' => $request->tel
      ]);
   }

   /**
    * Display the specified resource.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function show($id)
   {
      $address = Address::find($id);
      return response()->json($address);
   }

   /**
    * Update the specified resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function update(Request $request, $id)
   {
      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id

      Address::where('id', $id)->update([
         'user_id' => $user->id,
         'name' => $request->name,
         'provice' => $request->provice,
         'city' => $request->city,
         'area' => $request->area,
         'detail' => $request->detail,
         'tel' => $request->tel,
      ]);
   }

   /**
    * Remove the specified resource from storage.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function destroy($id)
   {
      Address::destroy($id);
   }

   /***
    *  设置默认地址
    */
   public function default_address(Request $request)
   {
      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id
      DB::table('users')->where('id', $user->id)->update(['address_id' => $request->address_id]);
   }
}
